package com.utils.basehelper.encrypt;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密解密
 */
public class EncryptUtils {
	private final static byte[] hex = "0123456789ABCDEF".getBytes();
	
	public static void main(String[] args) {
		try {
			long a = System.currentTimeMillis();
//	        System.out.println(encrypt("123rrrrr","13213132redesfe5"));
	        System.out.println(decrypt("A480B8054CECB1595EBC81ACD07B6C31","13213132redesfe5"));
	    	long b = System.currentTimeMillis();
	    	System.out.println(b-a);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 加密
	 * @param msg 明文
	 * @param password  密码
	 * @return 密文
	 * @throws Exception
	 */
	public static String encrypt(String msg,String password) throws Exception{
		if(msg==null){
			return "";
		}
		SecretKeySpec key = new SecretKeySpec(password.getBytes(),"AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte []bytes = cipher.doFinal(msg.getBytes("GBK"));
		return Bytes2HexString(bytes);
	}
	
	/**
	 * 解密
	 * @param msg 密文
	 * @param password 解密密码
	 * @return 明文
	 * @throws Exception
	 */
	public static String decrypt(String msg,String password) throws Exception{
		if(msg==null){
			return "";
		}
		SecretKeySpec key = new SecretKeySpec(password.getBytes(),"AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte []bytes = cipher.doFinal(HexString2Bytes(msg));
		return new String(bytes,"GBK");
	}
	
	private static int parse(char c) {
		if (c >= 'a')
			return (c - 'a' + 10) & 0x0f;
		if (c >= 'A')
			return (c - 'A' + 10) & 0x0f;
		return (c - '0') & 0x0f;
	}
	// 从字节数组到十六进制字符串转换
	public static String Bytes2HexString(byte[] b) {
		byte[] buff = new byte[2 * b.length];
		for (int i = 0; i < b.length; i++) {
			buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
			buff[2 * i + 1] = hex[b[i] & 0x0f];
		}
		return new String(buff);
	}

	// 从十六进制字符串到字节数组转换
	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parse(c0) << 4) | parse(c1));
		}
		return b;
	}
	
}

